package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

public class Threads
{
    private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    public static void sleep(long millseconds)
    {
        try
        {
            Thread.sleep(millseconds);
        }
        catch (InterruptedException e)
        {
            return;
        }
    }

    /**
     *  停止线程池
     *  先使用shutdown, 停止接收新任务并尝试完成所有已存在任务
     *
     * */
    public static void shutdownAndAwaitTermination(ExecutorService pool)
    {
        if(pool != null && !pool.isShutdown())
        {
            pool.shutdown();
            try
            {
                if(!pool.awaitTermination(120, TimeUnit.SECONDS))
                {
                    pool.shutdownNow();
                    if(!pool.awaitTermination(120, TimeUnit.SECONDS))
                    {
                        logger.info("pool did not terminate");
                    }
                }
            }
            catch (InterruptedException ie)
            {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
